const constants = require('../../constants.js')
const AUTH_LEVELS = constants.AUTH_LEVELS

Page({
  data: {
    devices: [],
    isScanning: false,
    isNormalMode: true,
    authLevel: wx.getStorageSync('authLevel') || 0,  // 获取用户权限等级
    AUTH_LEVELS: AUTH_LEVELS,  // 添加权限常量到 data 中
    showConnectModal: false,
    connectingDevice: null,
    connectProgress: 0,
    connectTimer: null,
    deviceTypes: [
      { id: 1, name: '窨井水位仪' },
      { id: 2, name: '水质流量主机' },
      { id: 3, name: '微型电子水尺' }
    ]
  },

  // 切换模式
  toggleMode() {
    const newMode = !this.data.isNormalMode
    this.setData({
      isNormalMode: newMode
    })
    wx.setStorageSync('isNormalMode', newMode)  // 保存模式状态
  },

  // 切换用户权限
  switchAuthLevel() {
    // 在开发模式下才允许切换权限
    if (!this.data.isNormalMode) {
      let newLevel = this.data.authLevel + 1
      if (newLevel > AUTH_LEVELS.DEVELOPER) {
        newLevel = AUTH_LEVELS.NORMAL
      }
      
      wx.setStorageSync('authLevel', newLevel)
      this.setData({ 
        authLevel: newLevel,
        showModeButton: newLevel === AUTH_LEVELS.DEVELOPER
      })

      // 显示当前权限等级
      let levelName = ''
      switch (newLevel) {
        case AUTH_LEVELS.NORMAL:
          levelName = '普通用户'
          break
        case AUTH_LEVELS.MAINTAIN:
          levelName = '运维人员'
          break
        case AUTH_LEVELS.ADVANCED:
          levelName = '高级用户'
          break
        case AUTH_LEVELS.DEVELOPER:
          levelName = '开发人员'
          break
      }

      wx.showToast({
        title: `已切换至${levelName}`,
        icon: 'none',
        duration: 2000
      })
    }
  },

  onLoad() {
    // 获取用户权限
    const authLevel = wx.getStorageSync('authLevel') || 0
    this.setData({ 
      authLevel,
      // 只有开发人员权限才显示模式切换按钮
      showModeButton: authLevel === AUTH_LEVELS.DEVELOPER
    })
    
    // 确保蓝牙适配器正确初始化
    this.initBluetooth()
  },

  // 页面显示时自动开始扫描
  onShow() {
    // 更新权限状态
    const authLevel = wx.getStorageSync('authLevel') || 0
    this.setData({ 
      authLevel,
      // 只有开发人员权限才显示模式切换按钮
      showModeButton: authLevel === AUTH_LEVELS.DEVELOPER
    })
    
    this.startBluetoothDevicesDiscovery()
  },

  // 初始化蓝牙
  initBluetooth() {
    // 先关闭蓝牙适配器
    wx.closeBluetoothAdapter({
      complete: () => {
        // 延迟后重新打开蓝牙适配器
        setTimeout(() => {
          wx.openBluetoothAdapter({
            success: (res) => {
              console.log('蓝牙初始化成功')
              this.startBluetoothDevicesDiscovery()
            },
            fail: (res) => {
              wx.showToast({
                title: '请打开蓝牙',
                icon: 'none'
              })
            }
          })
        }, 1000)
      }
    })
  },

  startBluetoothDevicesDiscovery() {
    if (this.data.isScanning) {
      this.stopBluetoothDevicesDiscovery()
      return
    }

    this.setData({ isScanning: true, devices: [] })
    
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      interval: 0,
      success: (res) => {
        wx.onBluetoothDeviceFound((result) => {
          const deviceList = result.devices.map(device => ({
            ...device,
            RSSI: device.RSSI,
            name: device.name || '未知设备',
            connected: false
          }))
          
          const allDevices = [...this.data.devices, ...deviceList]
          const sortedDevices = allDevices
            .sort((a, b) => b.RSSI - a.RSSI)
            .filter((device, index, self) => 
              index === self.findIndex(d => d.deviceId === device.deviceId)
            )

          this.setData({
            devices: sortedDevices
          })
        })
      }
    })
  },

  stopBluetoothDevicesDiscovery() {
    this.setData({ isScanning: false })
    wx.stopBluetoothDevicesDiscovery()
  },

  connectDevice(e) {
    const device = e.currentTarget.dataset.device
    // 先显示设备类型选择
    wx.showActionSheet({
      itemList: this.data.deviceTypes.map(type => type.name),
      success: (res) => {
        const selectedType = this.data.deviceTypes[res.tapIndex]
        this.startConnecting(device, selectedType)
      }
    })
  },

  // 开始连接设备
  startConnecting(device, deviceType) {
    // 先确保蓝牙适配器已关闭
    wx.closeBluetoothAdapter({
      complete: () => {
        // 重新初始化蓝牙适配器
        wx.openBluetoothAdapter({
          success: () => {
            this.proceedWithConnection(device, deviceType)
          },
          fail: (err) => {
            this.handleConnectionError('蓝牙初始化失败')
          }
        })
      }
    })
  },

  // 处理实际的连接逻辑
  proceedWithConnection(device, deviceType) {
    // 显示连接弹窗
    this.setData({
      showConnectModal: true,
      connectingDevice: device,
      connectProgress: 0
    })
    
    // 修改进度模拟逻辑
    let progress = 0
    const stages = [
      { target: 30, speed: 100 },
      { target: 60, speed: 150 },
      { target: 85, speed: 200 }
    ]
    let currentStage = 0

    this.connectTimer = setInterval(() => {
      if (currentStage < stages.length && progress < stages[currentStage].target) {
        progress += 1
      } else if (currentStage < stages.length - 1) {
        currentStage++
      } else if (progress >= 85) {
        clearInterval(this.connectTimer)
      }
      this.setData({ connectProgress: progress })
    }, 50)

    // 延迟一段时间再开始连接，确保蓝牙适配器已就绪
    setTimeout(() => {
      wx.createBLEConnection({
        deviceId: device.deviceId,
        timeout: 10000,
        success: () => {
          // 连接成功后，等待服务发现和特征值准备
          this.setData({ connectProgress: 90 })
          
          // 获取服务
          wx.getBLEDeviceServices({
            deviceId: device.deviceId,
            success: (res) => {
              this.setData({ connectProgress: 95 })
              const targetService = res.services.find(service => {
                const uuid = service.uuid.toUpperCase()
                return uuid.includes('FFF0')
              })
              
              if (targetService) {
                // 获取特征值
                wx.getBLEDeviceCharacteristics({
                  deviceId: device.deviceId,
                  serviceId: targetService.uuid,
                  success: (res) => {
                    clearInterval(this.connectTimer)
                    this.setData({ connectProgress: 100 })
                    
                    // 连接成功后延迟关闭弹窗并跳转
                    setTimeout(() => {
                      this.setData({ showConnectModal: false })
                      // 根据设备类型和模式跳转到不同页面
                      if (!this.data.isNormalMode) {
                        // 调试模式下跳转到debug页面
                        wx.navigateTo({
                          url: `/pages/debug/index?deviceId=${device.deviceId}`
                        })
                      } else {
                        // 正常模式下根据设备类型跳转
                        switch (deviceType.id) {
                          case 1: // 窨井水位仪
                            wx.navigateTo({
                              url: `/pages/device/index?deviceId=${device.deviceId}`
                            })
                            break
                          case 2: // 水质流量主机
                            wx.navigateTo({
                              url: `/pages/water-quality/index?deviceId=${device.deviceId}`
                            })
                            break
                          case 3: // 微型电子水尺
                            wx.navigateTo({
                              url: `/pages/water-ruler/index?deviceId=${device.deviceId}`
                            })
                            break
                        }
                      }
                    }, 500)
                  },
                  fail: (err) => {
                    this.handleConnectionError('获取特征值失败')
                  }
                })
              } else {
                this.handleConnectionError('未找到所需服务')
              }
            },
            fail: (err) => {
              this.handleConnectionError('获取服务失败')
            }
          })
        },
        fail: (err) => {
          this.handleConnectionError('连接失败')
        }
      })
    }, 1000)
  },

  // 添加连接错误处理函数
  handleConnectionError(message) {
    clearInterval(this.connectTimer)
    this.setData({ showConnectModal: false })
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    })
    // 关闭连接
    wx.closeBLEConnection({
      deviceId: this.data.connectingDevice.deviceId
    })
  },

  // 取消连接
  cancelConnection() {
    if (this.data.connectingDevice) {
      wx.closeBLEConnection({
        deviceId: this.data.connectingDevice.deviceId,
        complete: () => {
          clearInterval(this.connectTimer)
          this.setData({
            showConnectModal: false,
            connectingDevice: null,
            connectProgress: 0
          })
        }
      })
    }
  },

  onUnload() {
    // 清理定时器
    if (this.connectTimer) {
      clearInterval(this.connectTimer)
    }
  }
}) 